package chapter05.item29;

import java.util.Arrays;

/**
 * @author zhaoyuqiang
 * @date 2021年10月27日 16:40
 * @description 第29条：优先考虑泛型
 */
public class Stack1<E> {
    private E[] elements;
    private int size = 0;
    private static final int DEFAULT_INITIAL_CAPACITY = 16;

    @SuppressWarnings("unchecked")
    public Stack1(){
        elements = (E[]) new Object[DEFAULT_INITIAL_CAPACITY];
    }

    public void push(E e){
        ensureCapacity();
        elements[size++] = e;
    }

    public E pop(){
        if(size == 0){
            throw new EmptyStackException("数组为空，无法弹出");
        }
        E result = elements[--size];
        //这一步很重要，如果不把引用置空，会导致内存泄漏。
        elements[size] = null;
        return result;
    }

    public boolean isEmpty(){
        return size == 0;
    }

    private void ensureCapacity(){
        if(elements.length == size){
            elements = Arrays.copyOf(elements, 2 * size + 1);
        }
    }
}
